var app = getApp();
const Zan = require('../../../dist/index');
var Const = require('./../../../utils/const.js');
var Util = require('./../../../utils/util.js');

Page(Object.assign({}, Zan.TopTips, {

	data: {
		balance: 0,
		expireTime: 0,
		rechargable: false,
		selected: null,
		rechargeItems: []
	},

	itemSelect(e) {
		var that = this;
		var index = e.currentTarget.dataset.index;
		var rechargeItems = that.data.rechargeItems;
		var changed = {};

		for (var i in rechargeItems) {
			if (index == i) {
				changed['rechargeItems[' + i + '].checkClass'] = ' checked';
			} else {
				changed['rechargeItems[' + i + '].checkClass'] = '';
			}
		}

		if (index != null && index != undefined) {
			that.setData(Object.assign(changed, {
				selected: rechargeItems[index],
				rechargable: true
			}));

		} else {
			that.setData(Object.assign(changed, {
				selected: null,
				rechargable: false,
				rechargeItems: rechargeItems
			}));
		}
	},

	onLoad: function (options) {
		this.getRuleList();
	},

	onReady: function () {
		this.userinfo();
	},

	onShow: function () {

	},

	pay: function () {
		var that = this;

		if (that.data.rechargable) {
			// get price
			var total = that.data.selected.actualCharge, rechargeRuleId = that.data.selected.id;
			if (that.data.selected && total > 0) {
				app.wechat.getStorage(Const.DATA.KEY_MEMBER).then(function (res) {
					app.data.member = res.data;
					var balance = app.data.member.walletMoney - app.data.member.tradeMoney;
					if ((balance - total) < 0) {
						that.showZanTopTips('余额不足，请去充值', {type: 'error'});
						return;
					}

					app.battery.common('monthRecharge/prePay', {
						total: total,
						rechargeRuleId: rechargeRuleId,
						ticket: app.data.token
					}).then(function (d) {
						app.wechat.setStorage(Const.DATA.KEY_MEMBER, d);
						app.data.member = d;
						wx.navigateBack({
							delta: 1
						});
					}).catch(function (e) {
						that.showZanTopTips(e.message, {type: 'error'});
					});
				});
			} else {
				that.showZanTopTips('金额不得小于0', {type: 'error'});
			}
		}
	},

	getRuleList: function () {
		var that = this;
		var rechargeItems = [];

		app.battery.common('rule/list', {type: 2}).then(function (d) {
			d.forEach(v => {
				rechargeItems.push({
					id: v.id,
					actualCharge: v.actualCharge / 100.0,
					presentedCharge: v.presentedCharge / 100.0
				})
			});

			that.setData({
				rechargeItems: rechargeItems
			})
		}).catch(function (e) {
			that.showZanTopTips(e.message, {type: 'error'});
		});
	},

	userinfo: function () {
		var that = this;

		app.battery.findOne('member/detail', app.data.member.id).then(function (r) {
			console.log(r);
			that.setData({
				balance: (r.monthWalletMoney - r.monthTradeMoney).toFixed(2),
				expireTime: r.monthExpireTime ? Util.formatDate(new Date(r.monthExpireTime * 1000), 'yyyy-MM-dd hh:mm') : '',
			});
		}).catch(function (e) {
			that.showZanTopTips(e.message, {type: 'error'});
		});
	},
}));